#pragma once
#include <string>
#include <unordered_map>
#include <fstream> //file
#include "Log.hpp"

const char *sep = ": ";

class Dict // 字典unordered_map
{
    // 1.txt加载到unordered_map
    void LoadDict()
    {
        std::ifstream in(_path); // 以读打开文件
        if (!in.is_open())
        {
            Log(FATAL, "open file fail");
            exit(-1);
        }
        Log(INFO, "open file success");

        while (!in.eof()) // End Of File, 读到结尾返回ture退出
        {
            std::string temp; // 每趟都会重新创建初始化
            std::getline(in, temp);
            if (temp.empty())
                continue;               // 读到空行跳过
            int index = temp.find(sep); // 返回下标
            if (index == temp.npos)
                continue;                               // 没找到,跳过
            std::string left = temp.substr(0, index);   // 下标==前面的个数
            //std::cout << strlen(sep) << std::endl;
            std::string right = temp.substr(index+strlen(sep));     // 默认读到结尾
            _dict.emplace(std::make_pair(left, right)); //(函数模板会自动推到类型)//_dict.emplace(std::pair<std::string, std::string>(left, right));
        }

        in.close();
    }

public:
    Dict(std::string path)
        : _path(path)
    {
        LoadDict();
    }

    // 2.翻译
    std::string Translate(std::string word)
    {
        std::unordered_map<std::string, std::string>::iterator it = _dict.find(word);
        //atuo it = _dict.find(word);
        if (it != _dict.end())
            return it->second;
        else 
            return "None";
    }

    ~Dict()
    {
    }

private:
    std::string _path;
    std::unordered_map<std::string, std::string> _dict;
};